import axios from 'axios'
import qs from 'qs'
import {
  Message
} from 'element-ui';
import router from '../router/index'
import merge from 'lodash/merge'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
  withCredentials: true, // send cookies when cross-domain requests
  timeout: 5000, // request timeout
});

// axios拦截器
service.interceptors.request.use(request => {
  request.headers['Content-Type'] = 'application/json';
  let token = sessionStorage.getItem("security_yuyao_token")
  if (token) {
    request.headers['security_yuyao_token'] = token
  }
  // request.baseURL = process.env.baseURL
  return request;

});

// 拦截响应
service.interceptors.response.use((response) => {
  if (response.data.code == 401) {
    Message({
      message: response.data.msg,
      type: 'warning'
    });
    router.push({
      path: "/",
      query: {}
    })
    return response.data;
  } else {
    return response.data
  }
},
  service.adornData = (data = {}, openDefultdata = true, contentType = 'json') => {
    var defaults = {
      't': new Date().getTime()
    }
    data = openDefultdata ? merge(defaults, data) : data
    return contentType === 'json' ? JSON.stringify(data) : qs.stringify(data)
  },

  error => {
    return Promise.reject(error.message); // 返回接口返回的错误信息
  });

export default service;